package cn.kk.communication.dao;
/*
 *@author KK on 2022.09.12 1:23
 */

import cn.kk.communication.entity.Communication;
import cn.kk.communication.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao<T> implements Dao<T> {
    Class<T> clazz = null;

    //获取带泛型类的类
    public BaseDao() {
        Type type = this.getClass().getGenericSuperclass();
        //参数化类型
        ParameterizedType pt = (ParameterizedType) type;
        //获取真实的参数
        Type[] types = pt.getActualTypeArguments();
        //传进来的第一个类就是我们想要的类
        clazz = (Class<T>) types[0];
    }

    private QueryRunner qr = new QueryRunner();
    private QueryRunner qrNot = new QueryRunner(DBUtils.getDataSource());

    @Override
    public Object getValue(Connection conn, String sql, Object... params) throws SQLException {
        return qr.query(conn, sql, new ScalarHandler<>(),params);
    }

    @Override
    public List<T> queryAll(Connection conn, String sql, Object... params) throws SQLException {
        return (List<T>) qr.query(conn, sql, new BeanListHandler<>(clazz), params);
    }

    @Override
    public T query(Connection conn, String sql, Object... params) throws SQLException {
        return qr.query(conn, sql, new BeanHandler<>(clazz), params);
    }

    @Override
    public int update(Connection conn, String sql, Object... params) throws SQLException {
        return qr.update(conn, sql, params);
    }

    /**
     * 不考虑事务的通用dao
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    @Override
    public Object getValue(String sql, Object... params) throws SQLException {
        return qrNot.query(sql, new ScalarHandler<>());
    }

    @Override
    public List<T> queryAll(String sql, Object... params) throws SQLException {
        return (List<T>) qrNot.query(sql, new BeanListHandler<>(clazz), params);
    }

    @Override
    public T query(String sql, Object... params) throws SQLException {
        return qrNot.query(sql, new BeanHandler<>(clazz), params);
    }

    @Override
    public int update(String sql, Object... params) throws SQLException {
        return qrNot.update(sql, params);
    }

}
